<template>
    <el-form :model="formData" label-width="120px" ref="form" v-loading="loading" class="pr-4">
        <el-form-item label="上级id" prop="parent_id">
            <el-cascader v-model="formData.parent_id" name="parent_id" :filterable="true" :options="options" clearable
                         class="w-full" :show-all-levels="false" :props="{ value: 'id', label: 'name', checkStrictly: true }"/>
        </el-form-item>
        <el-form-item label="名称" prop="name" required>
            <el-input v-model="formData.name" name="name" clearable/>
        </el-form-item>
        <div class="flex justify-end">
            <el-button type="primary" @click="submitForm(form)">{{ $t('system.confirm') }}</el-button>
        </div>
    </el-form>
</template>

<script lang="ts" setup>
import {useCreate} from '@/composables/curd/useCreate'
import {useShow} from '@/composables/curd/useShow'
import {onMounted, ref, unref} from 'vue'
import http from "@/support/http";

const props = defineProps({
    primary: [String, Number],
    api: String,
})

const {formData, form, loading, submitForm, close, beforeCreate, beforeUpdate} = useCreate(props.api, props.primary)

if (props.primary) {
    useShow(props.api, props.primary, formData)
}

const emit = defineEmits(['close'])
const options = ref([])
beforeCreate.value = () => {
    formData.value.parent_id = getParent(formData.value.parent_id)
}

beforeUpdate.value = () => {
    formData.value.parent_id = getParent(formData.value.parent_id)
}

const getParent = (parentId: any) => {
    return typeof parentId === 'undefined' ? 0 : parentId[parentId.length - 1]
}

if (props.primary) {
    const { afterShow } = useShow(props.api, props.primary, formData)
    afterShow.value = formData => {
        const data = unref(formData)
        data.parent_id = data.parent_id ? [data.parent_id] : 0
        formData.value = data
    }
}
onMounted(() => {
    close(() => emit('close'))
    http.get(props.api).then(res => {
        options.value = res.data.data
    });
})
</script>
